<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\command;

use app\common\model\book\Category;
use app\common\model\book\Book as BookModel;
use app\common\model\book\Chapter as ChapterModel;
use app\common\model\book\BookExtra as BookExtraModel;
use app\common\model\pull\Pull as PullModel;
use app\common\model\pull\PullLog as PullLogModel;
use app\common\service\ContentService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;


class FirstPull extends Command
{
    protected function configure()
    {
        $this->setName('first_pull')
            ->setDescription('拉取书籍数据');
    }

    public $category = [
        1=>1,
        2=>2,
        3=>3,
        4=>4,
        7=>5,
        6=>6,
        999=>7,
        41=>8,
        42=>9,
        43=>10,
        44=>11,
        45=>12,
        46=>13,
        47=>14,
        998=>15,
    ];

    protected function execute(Input $input, Output $output)
    {
        try {
            $pull = PullModel::where("online","=",1)->where("id","=",1)->select();

            if($pull){
                foreach ($pull as $k=>$v){
                    $spiderid = $v["id"];
                    $bookArr = BookModel::where("siteid","=",$spiderid)->column('sourceid');
                    //日志文件
                    //$logfile = $this->makelog($spiderid);
                    $logfile = '';
                    //1.查询第三方所有授权书籍
                    $book_list = array(
                        array("sourceid" => "3003307"),
                        array("sourceid" => "2069977"),
                        array("sourceid" => "3009691"),
                        array("sourceid" => "3017148"),
                        array("sourceid" => "2070000"),
                        array("sourceid" => "3016098"),
                        array("sourceid" => "3017163"),
                        array("sourceid" => "3016099"),
                        array("sourceid" => "3025764"),
                        array("sourceid" => "3015794"),
                        array("sourceid" => "3025763"),
                        array("sourceid" => "3025938"),
                        array("sourceid" => "3026013"),
                        array("sourceid" => "3015827"),
                        array("sourceid" => "3013438"),
                        array("sourceid" => "3026120"),
                        array("sourceid" => "3026119"),
                        array("sourceid" => "3025790"),
                        array("sourceid" => "3026122"),
                        array("sourceid" => "3025720"),
                        array("sourceid" => "3025749"),
                        array("sourceid" => "3025820"),
                        array("sourceid" => "3025696"),
                        array("sourceid" => "3025761"),
                        array("sourceid" => "3025794"),
                        array("sourceid" => "3025791"),
                        array("sourceid" => "3026117"),
                        array("sourceid" => "3025718"),
                    );
                    if($book_list){
                        foreach ($book_list as $bk=>$bv){
                            //判断是否已经拉取过书籍
//                            if (!in_array($bv["sourceid"], $bookArr)){
                            echo date('Y-m-d H:i:s')."书籍拉取开始--".$bv["sourceid"].PHP_EOL;
                            $chapter_list = $this->get_chapter_list($v,$bv["sourceid"],$logfile);
                            if($chapter_list){
                                $bookinfo  =BookModel::where("siteid","=",$spiderid)->where("sourceid","=",$bv["sourceid"])->find();
                                foreach ($chapter_list as $ck=>$cv){
                                    if (!empty($cv)){
                                        $chapterinfo = ChapterModel::suffix(getSuffix($bookinfo["id"]))->where('siteid',$spiderid)->where('sourceid',$bv["sourceid"])->where('sourcecid',$cv['sourcecid'])->findOrEmpty();
                                        if($chapterinfo->isEmpty()){
                                            $this->get_chapter_info($bookinfo,$v,$bv,$cv,"add");
                                        }else{
                                            if ($cv['update_time']>$bookinfo['pulltime']){
                                                $this->get_chapter_info($bookinfo,$v,$bv,$cv,"edit",$chapterinfo);
                                            }else{
                                                echo date('Y-m-d H:i:s')."书籍章节无需更新--".$bv["sourceid"].PHP_EOL;
                                            }
                                        }
                                    }else{
                                        echo date('Y-m-d H:i:s')."书籍章节不存在--".$bv["sourceid"].PHP_EOL;
                                    }
                                }
                                $lastChapter = ChapterModel::suffix(getSuffix($bookinfo["id"]))->where('book_id',$bookinfo["id"])->order('chapter_order desc')->findOrEmpty();
                                if (!$lastChapter->isEmpty()){
                                    BookModel::where('id',$bookinfo["id"])->update(['last_chapter_id'=>$lastChapter['chapter_id'],'last_chapter_name'=>$lastChapter['chapter_name']]);
                                }else{
                                    //没有章节设置为异常书籍
                                    BookModel::where('id',$bookinfo["id"])->update(['third_status'=>5]);
                                }
                            }else{
                                continue;
                            }
                            echo date('Y-m-d H:i:s')."书籍拉取结束--".$bv["sourceid"].PHP_EOL;
//                            }else{
//                                echo date('Y-m-d H:i:s')."书籍已拉取--".$bv["sourceid"].PHP_EOL;
//                            }

                        }
                    }
                }
            }
        } catch (\Exception $e) {
            Log::write('书籍同步失败:' . $e->getMessage());
            return false;
        }
    }

    /**
     * get_chapter_list [抓取章节列表]
     *
     * @param type $pull      [抓取配置信息]
     * @param type $articleid [抓取的书籍ID]
     * @param type $logfile   [desc]
     *
     * @return type
     **/
    public function  get_chapter_list($pull,$articleid,$logfile) {

        $bookinfo_url = $pull["bookinfo_url"];
        $chapterlist_url = $pull["chapterlist_url"];
        if(strpos($chapterlist_url,"http://")===false || strpos($bookinfo_url,"http://")===false){
            $this->writelog($pull,0,0,0,0,"分析接口URI失败！".$chapterlist_url);
        }else{
            $bookinfo_url = str_replace("{bookid}",$articleid,$bookinfo_url);
            $queryString = $this->formatQueryString([],$pull["app_key"],$pull["app_secret"]);
            $bookinfo_url = $bookinfo_url.'?'.$queryString;
            //获取书籍信息
            $articleinfos = json_decode(file_get_contents($bookinfo_url),true);
            if ($articleinfos["result"]["status"]["code"]!=0){
                echo date('Y-m-d H:i:s')."--".$articleid.$articleinfos["result"]["status"]["msg"].PHP_EOL;
                return false;
            }
            if($pull["id"]==1){
                $is_online = $articleinfos["result"]["data"]["is_online"]??0;
                $channel_type = $articleinfos["result"]["data"]["category_info"]["site"]??0;
                $sortid = $articleinfos["result"]["data"]["category_info"]["bid"]??0;
                //如果没有分类字段，判定为异常书籍
                if($channel_type!=0&&$sortid!=0){
                    if ($is_online==1){
                        $third_status = 1;
                    }elseif ($is_online==0){
                        $third_status = 4;
                    }
                }else{
                    $third_status = 5;
                }

                $articleinfo["data"] = [
                    "channel_id"=>$articleinfos["result"]["data"]["channel_id"],
                    "channel_name"=>$articleinfos["result"]["data"]["channel_name"],
                    "sourceid"=>$articleinfos["result"]["data"]["book_id"],
                    "book_name"=>$articleinfos["result"]["data"]["book_title"],
                    "pulltime"=>time(),
                    "author"=>$articleinfos["result"]["data"]["author_name"],
                    "keyword"=>trim($articleinfos["result"]["data"]["plotlabel"], ','),
                    "intro"=>$articleinfos["result"]["data"]["book_intro"],
                    "fullflag"=>$articleinfos["result"]["data"]["writing_process"],
                    "chapter_count"=>$articleinfos["result"]["data"]["chapter_count"],
//                    "thousand_word_price"=>$articleinfos["result"]["data"]["k_word_price"],
                    "thousand_word_price"=>45,//默认千字45书币
                    "pay_chapter"=>$articleinfos["result"]["data"]["pay_n_chapter"],
                    "word_count"=>$articleinfos["result"]["data"]["word_count"],
                    "sortid"=>$sortid,
                    "thumb"=>$articleinfos["result"]["data"]["cover_url"],
                    "shield"=>$articleinfos["result"]["data"]["is_delete"],
                    "third_status"=>$third_status,
                    "channel_type"=>$channel_type,
                ];
            }else{
                $articleinfo = $articleinfos;
            }

            if($articleinfo&&is_array($articleinfo)&&$articleinfo["data"]){


                if(intval($articleinfo["data"]["sourceid"])==0||$articleinfo["data"]["book_name"]==""||$articleinfo["data"]["author"]==""){
                    $this->writelog($pull,0,$articleinfo["data"],0,0,"小说信息不完整，缺失ID/名称/作者，抓取失败！".$bookinfo_url);
                    return false;
                }

                //不存在则添加书籍信息
                $book_id = 0;

                $is_article = BookModel::where("siteid","=",$pull["id"])->where("sourceid","=",$articleinfo["data"]["sourceid"])->findOrEmpty();

                if($is_article->isEmpty()){
                    if(empty($articleinfos["result"]["data"]["cover_url"])||!imageExists($articleinfos["result"]["data"]["cover_url"])){
                        //没有封面给默认书封
                        $thumbUrl = 'static/images/nocover.jpg';
//                        $this->writelog($pull,0,$articleinfo["data"],0,0,"图片不存在，抓取失败！".$bookinfo_url);
//                        return false;
                    }else{
                        $thumbUrl = ContentService::uploadByUrl($articleinfo["data"]["thumb"]);
                    }

//                    if (empty($articleinfos["result"]["data"]["category_info"]["bid"])){
//                        $this->writelog($pull,0,$articleinfo["data"],0,0,"分类匹配失败，抓取失败！".$bookinfo_url);
//                        return false;
//                    }

                    $param = [
                        "channel_id"=>$articleinfo["data"]["channel_id"],
                        "channel_name"=>$articleinfo["data"]["channel_name"],
                        "poster"=>$pull['name'],
                        "siteid"=>$pull['id'],
                        "sourceid"=>$articleinfo["data"]["sourceid"],
                        "book_name"=>$articleinfo["data"]["book_name"],
                        "keyword"=>$articleinfo["data"]["keyword"],
                        "channel_type"=>$articleinfo["data"]["channel_type"],
                        "sort_id"=>$this->category[$articleinfo["data"]["sortid"]]??0,
                        "author"=>$articleinfo["data"]["author"],
                        "intro"=>$articleinfo["data"]["intro"],
                        "fullflag"=>$articleinfo["data"]["fullflag"],
                        "shield"=>$articleinfo["data"]["shield"],
                        "chapter_count"=>$articleinfo["data"]["chapter_count"],
                        "word_count"=>$articleinfo["data"]["word_count"],
//                        "pay_chapter"=>$articleinfo["data"]["pay_chapter"],
                        "thousand_word_price"=>$articleinfo["data"]["thousand_word_price"],
                        "pulltime"=>time(),
                        "virtual_readnum"=>rand(10000, 500000),
                        "thumb"=>$thumbUrl,
                        "third_status"=>$articleinfo["data"]["third_status"]??0,
                        "is_vip"=>1
                    ];

                    $result = BookModel::create($param);
                    $book_id = $result['id'];
                    if($book_id) {
                        $extraData = [
                            'book_id' => $book_id,
                            'pay_chapter' => $articleinfo["data"]["pay_chapter"],
                        ];
                        BookExtraModel::create($extraData);
                    }

                    $is_article = BookModel::where("siteid","=",$pull["id"])->where("sourceid","=",$articleinfo["data"]["sourceid"])->findOrEmpty();

                    $this->writelog($pull,$book_id,$articleinfo["data"],0,1,"小说信息入库成功！");
                }else{
                    //如果书籍已经抓取，判断是否完结，完结书籍不操作
                    if($is_article->fullflag==1){
                        echo date('Y-m-d H:i:s')."小说已经完本，停止抓取！--".$is_article->id.PHP_EOL;
//                        $this->writelog($pull,$is_article->id,$articleinfo["data"],0,0,"小说已经完本，停止抓取！".$bookinfo_url);
                        return false;
                    }
                    echo date('Y-m-d H:i:s')."更新书籍信息--".$is_article->id.PHP_EOL;
                    $is_article->book_name = $articleinfo["data"]["book_name"];
                    $is_article->keyword = $articleinfo["data"]["keyword"];
                    $is_article->author = $articleinfo["data"]["author"];
                    $is_article->intro = $articleinfo["data"]["intro"];
                    $is_article->fullflag = $articleinfo["data"]["fullflag"];
                    $is_article->shield = $articleinfo["data"]["shield"];
                    $is_article->chapter_count = $articleinfo["data"]["chapter_count"];
                    $is_article->word_count = $articleinfo["data"]["word_count"];
                    $is_article->pulltime = time();
                    $is_article->save();
                    BookExtraModel::where('book_id',$is_article->id)->update(['pay_chapter'=>$articleinfo["data"]["pay_chapter"]]);
                }

                //获取章节信息
                $chapterData = [];
                for ($i = 1; $i < 1000; $i++) {
                    $chapterlist_url = str_replace("{bookid}",$articleid, $pull["chapterlist_url"]);
                    $bookQueryString = $this->formatQueryString(['page'=>$i],$pull["app_key"],$pull["app_secret"]);
                    $chapterlist_url = $chapterlist_url.'?'.$bookQueryString;
                    $chapterlistdata = json_decode(file_get_contents($chapterlist_url),true);
                    if(is_array($chapterlistdata['result']['data'])){
                        $chapterData[] = $chapterlistdata['result']['data'];
                    }

                    if (count($chapterlistdata['result']['data']) < 200||is_array($chapterlistdata['result']['data'])==false) {
                        break; // 当数据小于200时跳出循环
                    }
                }
                $chapterlist = [];
                if($pull["id"]==1){
                    $chaplist=$chapterData;
                    if($chaplist){
                        if(!empty($chaplist)){
                            foreach ($chaplist as $kk=>$vv){
                                foreach ($vv as $k=>$v){
                                    $chapterlist["data"][] = [
                                        "sourceid"=>$v["book_id"],
                                        "sourcecid"=>$v["content_id"],
                                        "chapter_name"=>$v["norm_title"],
                                        "book_id"=>$is_article->id??0,
                                        "book_name"=>$is_article->book_name??'',
                                        "checkname"=>$v["title"],
                                        "chapter_order"=>$v["order"],
                                        "is_vip"=>($v["price"] == 0) ? 0 : 1,
                                        "price"=>round($v['word_count']/1000*$is_article->thousand_word_price),
                                        "authtime"=>time(),
                                        "create_time"=>strtotime($v["create_time"]),
                                        "update_time"=>strtotime($v["edit_time"]),
                                        "word_count"=>$v["word_count"],
                                        "is_delete"=>$v["is_delete"],
                                    ];
                                }
                            }
                        }else{
                            $chapterlist["data"][] = [];
                        }
                    }
                }else{
                    $chapterlist = $chapterlistdata;
                }

                if(($chapterlist && !is_array($chapterlist["data"]))|| ($chapterlist &&count($chapterlist["data"])<1)){
                    $this->writelog($pull,$book_id,$articleinfo["data"],0,0,"获取小说章节列表失败！".$chapterlist_url);
                    return false;
                }

                $this->writelog($pull,$book_id,$articleinfo["data"],0,1,"获取小说章节列表成功！");
            }

            return $chapterlist["data"];
        }
    }

    /**
     * get_chapter_info [章节详情抓取]
     *
     * @param type $bookinfo  [本站书籍入库信息]
     * @param type $pull      [抓取配置信息]
     * @param type $book	   [抓取的书籍信息]
     * @param type $chapter   [抓取的章节信息]
     * @param type $logfile   [日志路径]
     *
     * @return type
     **/
    public function get_chapter_info($bookinfo,$pull,$book,$chapter,$type="add",$chapterinfo=array()) {

        $chaptercontent_url = $pull['chaptercontent_url'];
        $sourceid = $chapter['sourceid'];
        if(strpos($chaptercontent_url,"http://")===false ){
            $this->writelog($pull,$bookinfo["id"],$bookinfo,$chapter,0,"分析接口URI失败！".$chaptercontent_url);
        }else{
            $chapter['sourcecid'] = $chapter['sourcecid'];
            $chaptercontent_url = str_replace(["{bookid}","{chapterid}"],[$sourceid,$chapter['sourcecid']],$chaptercontent_url);
            $queryString = $this->formatQueryString([],$pull["app_key"],$pull["app_secret"]);
            $chaptercontent_url = $chaptercontent_url.'?'.$queryString;
            $chaptercontentdata = json_decode(file_get_contents($chaptercontent_url),true);
            if($chaptercontentdata && $chaptercontentdata['result']['data'] && !empty($chaptercontentdata['result']['data']['content'])){
                $content = $this->foramtContent($chaptercontentdata['result']['data']['content']);
                if($type=="edit"){
                    echo date('Y-m-d H:i:s')."编辑章节--".$chapterinfo['chapter_id'].PHP_EOL;
                    $chapterdata['chapter_id'] = $chapterinfo["chapter_id"];
                    $contentUrl = ContentService::uploadContent($bookinfo["id"],$chapterdata['chapter_id'],$content);
                    $summary = truncateAfterLastClosingPTag(mb_substr($content,0,200));
                    $chapterdata['siteid'] = $pull["id"];
                    $chapterdata['sourceid'] = $sourceid;
                    $chapterdata['sourcecid'] = $chapter['sourcecid'];
                    $chapterdata['book_id'] = $bookinfo["id"];
                    $chapterdata['book_name'] = $bookinfo["book_name"];
                    $chapterdata['chapter_name'] = $chapter["chapter_name"];
                    $chapterdata['checkname'] = $chapter["checkname"];
                    $chapterdata['is_vip'] =$chapter["is_vip"];
                    $chapterdata['price'] =$chapter["price"];
                    $chapterdata['chapter_order'] =$chapter["chapter_order"];
                    $chapterdata['word_count'] =$chapter["word_count"];
                    $chapterdata['content_url'] =$contentUrl;
                    $chapterdata['summary'] =$summary;
                    $chapterdata['create_time'] =$chapter["create_time"];
                    $chapterdata['update_time'] =$chapter["update_time"];
                    ChapterModel::suffix(getSuffix($bookinfo["id"]))->where('chapter_id',$chapterdata['chapter_id'])->update($chapterdata);
                }else{
                    echo date('Y-m-d H:i:s')."新增章节--".$sourceid.'章节名称'.$chapter["chapter_name"].PHP_EOL;
                    $chapterdata['siteid'] = $pull["id"];
                    $chapterdata['sourceid'] = $sourceid;
                    $chapterdata['sourcecid'] = $chapter['sourcecid'];
                    $chapterdata['book_id'] = $bookinfo["id"];
                    $chapterdata['book_name'] = $bookinfo["book_name"];
                    $chapterdata['chapter_name'] = $chapter["chapter_name"];
                    $chapterdata['checkname'] = $chapter["checkname"];
                    $chapterdata['is_vip'] =$chapter["is_vip"];
                    $chapterdata['price'] =$chapter["price"];
                    $chapterdata['chapter_order'] =$chapter["chapter_order"];
                    $chapterdata['word_count'] =$chapter["word_count"];
                    $chapterdata['create_time'] =$chapter["create_time"];
                    $chapterdata['update_time'] =$chapter["update_time"];
                    $chapterdata['authtime'] =$chapter["authtime"];
                    $chapter_id = ChapterModel::suffix(getSuffix($bookinfo["id"]))->insertGetId($chapterdata);
                    $contentUrl = ContentService::uploadContent($bookinfo["id"],$chapter_id,$content);
//                    $summary = mb_substr(strip_tags($content),0,200);
                    $summary = truncateAfterLastClosingPTag(mb_substr($content,0,200));
                    ChapterModel::suffix(getSuffix($bookinfo["id"]))->where('chapter_id',$chapter_id)->update(['content_url'=>$contentUrl,'summary'=>$summary]);
                }
                echo date('Y-m-d H:i:s')."获取章节内容成功--书籍名称 ： ".$bookinfo["book_name"].'章节名称 ： '.$chapter["chapter_name"].PHP_EOL;
                $this->writelog($pull,$bookinfo["id"],$bookinfo,$chapter,1,"获取章节内容成功！");
            }else{

                $this->writelog($pull,$bookinfo["id"],$bookinfo,$chapter,0,"获取章节内容失败！");
                return false;
            }
        }

    }

    private function foramtContent($content) {

        $result = '';
        $lines = explode("\n", $content);
        foreach ($lines as $line) {
            $result .= "<p>$line</p>";  // 使用循环将每一行文本用 <p> 标签包裹起来
        }
        return $result;
    }

    private function formatQueryString($params,$appKey,$appSecret){
        $params['req_time'] = time().str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $params['app_secret'] = $appSecret;
        $params['access_token'] = $this->getAccessToken($params);
        $params['app_key'] = (int)$appKey;
        unset($params['app_secret']);
        $queryString = http_build_query($params);
        return $queryString;
    }
    function getAccessToken($params) {
        // 排除键值是app_key、app_token的参数数据

        // 按ASCII排序
        ksort($params);

        // 重置指针
        reset($params);

        // 组装成键值对的字符串格式
        $queryString = '';
        foreach ($params as $key => $value) {
            $queryString .= $key . '=' . $value . '&';
        }
        // 添加app_secret
        $queryString = rtrim($queryString, '&');
        // md5加密
        $accessToken = md5($queryString);

        return $accessToken;
    }

    public function get_book_list($pull,$logfile) {

        if(strpos($pull["booklist_url"],"http://")===false){
            $this->writelog($pull,0,0,0,0,"获取小说列表失败！");
            return false;
        }else{
            if($pull['id']==1){
                $bookListDataArr = [];
//                $edit_time = date('Y-m-d H:i:s',time());
                $edit_time = '2024-05-15 00:00:00';
                for ($i = 1; $i < 1000; $i++) {
                    $queryString = $this->formatQueryString(['page'=>$i,'edit_time'=>$edit_time],$pull["app_key"],$pull["app_secret"]);
                    $url = $pull["booklist_url"].'?'.$queryString;
                    $bookListData = json_decode(file_get_contents($url),true);
                    if(is_array($bookListData['result']['data'])){
                        $bookListDataArr[] = $bookListData['result']['data'];
                    }

                    if (count($bookListData['result']['data']) < 200||is_array($bookListData['result']['data'])==false) {
                        break; // 当数据小于200时跳出循环
                    }
                }
                if($bookListDataArr && is_array($bookListDataArr)) {
                    $data = array();
                    foreach ($bookListDataArr as $kk=>$vv){
                        foreach ($vv as $k=>$v){
                            if (isset($v["category_info"]['site'])&&isset($v["category_info"]['bid'])){
                                $data[] = [
                                    "sourceid"=>$v["book_id"]??null,
                                    "book_name"=>$v["book_title"]??null,
                                    "siteid"=>$v["channel_id"]??null,
                                    "author"=>$v["author_name"]??null,
                                    "third_status"=>$v["is_online"]??null,
                                    "keyword"=>$v["plotlabel"]??null,
                                    "word_count"=>$v["word_count"]??null,
                                    "chapter_count"=>$v["chapter_count"]??null,
                                    "fullflag"=>$v["writing_process"]??null,
                                    "channel_type"=>$v["category_info"]['site']??null,
                                    "sort_id"=>$v["category_info"]['bid']??null,
                                    "pull_time"=>$v["edit_time"]??null,
                                ];
                            }else{
                                $data[] = [
                                    "sourceid"=>$v["book_id"]??null,
                                    "book_name"=>$v["book_title"]??null,
                                    "siteid"=>$v["channel_id"]??null,
                                    "author"=>$v["author_name"]??null,
                                    "third_status"=>5,
                                    "keyword"=>$v["plotlabel"]??null,
                                    "word_count"=>$v["word_count"]??null,
                                    "chapter_count"=>$v["chapter_count"]??null,
                                    "fullflag"=>$v["writing_process"]??null,
                                    "channel_type"=>1,
                                    "sort_id"=>1,
                                    "pull_time"=>$v["edit_time"]??null,
                                ];
                            }
                        }
                    }
                    return $data;
                }else{
                    $this->writelog($pull,0,0,0,0,"小说列表数据为空！".$pull["booklist_url"]);
                }
            }else{
                $this->writelog($pull,0,0,0,0,"小说列表数据为空！".$pull["booklist_url"]);
            }
        }
    }

    /**
     * writelog [desc]
     *
     * @param type $pull    [抓取配置信息]
     * @param type $book_id [本站书籍ID]
     * @param type $book    [抓取书籍信息]
     * @param type $chapter [抓取章节信息]
     * @param type $status  [抓取状态]
     * @param type $content [抓取描述]
     *
     * @return type
     **/

    //public function writelog($logfile,$msg) {
    public function writelog($pull,$book_id,$book,$chapter,$status,$content) {

        //file_put_contents($logfile, date('Y-m-d H:i:s').$msg.PHP_EOL, FILE_APPEND);
        if($pull){
            $param["ssid"]=$pull['id'];
            $param["ssname"]=$pull['name'];
        }

        if($book_id){
            $param["book_id"]=$book_id;
        }

        if($book){
            $param["pull_book_id"]=$book['sourceid']?$book['sourceid']:0;
            $param["pull_book_name"]=$book['book_name'];
        }
        if($chapter){
            $param["pull_chapter_id"]=$chapter['chapter_id']??0;
            $param["pull_chapter_name"]=$chapter['chapter_name'];
        }
        $param["status"]=$status;
        $param["content"]=$content;

        Db::startTrans();
        try {
            PullLogModel::create($param);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

}